import pandas as pd

class ExcelExporter:
    """
    A class to export analysis results to an Excel file.
    """
    def __init__(self, columns_order=None):
        if columns_order is None:
            self.columns_order = [
                'file_name', 
                'overall_score', 
                'skill_match', 
                'experience_match', 
                'education_match', 
                'recommendation', 
                'concerns', 
                'processed_time', 
                'file_path'
            ]
        else:
            self.columns_order = columns_order

    def export(self, results, output_path):
        """
        Exports the given results to an Excel file.

        Args:
            results (list): A list of dictionaries, where each dictionary is a result for a resume.
            output_path (str): The path to save the Excel file to.
        """
        if not results:
            print("No results to export.")
            return

        df = pd.DataFrame(results)
        
        # Ensure all columns exist, fill missing ones with None
        for col in self.columns_order:
            if col not in df.columns:
                df[col] = None
        
        # Reorder columns
        df = df[self.columns_order]

        try:
            with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
                df.to_excel(writer, sheet_name='简历筛选结果', index=False)
                
                # Auto-adjust column width, as in the tutorial
                worksheet = writer.sheets['简历筛选结果']
                for column in worksheet.columns:
                    max_length = 0
                    column_letter = column[0].column_letter
                    for cell in column:
                        try:
                            if len(str(cell.value)) > max_length:
                                max_length = len(str(cell.value))
                        except:
                            pass
                    adjusted_width = min(max_length + 2, 50) # Cap width at 50
                    worksheet.column_dimensions[column_letter].width = adjusted_width
            
            print(f"Successfully exported results to: {output_path}")

        except Exception as e:
            print(f"Failed to export results to Excel: {e}")